//
//  NetworkManager.swift
//  weibo
//
//  Created by Fly on 2018/1/23.
//  Copyright © 2018年 Fly. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

// Swift 的枚举支持任意数据类型
enum HTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class NetworkManager: AFHTTPSessionManager {

//    static let networkManager = NetworkManager()
    
    static let networkManager: NetworkManager = {
        
        let instance = NetworkManager()
        
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
        
        }()
    
//    var accessToken: String? //= "2.00VUlvCHI4HDAC7d4d8dd38ePs6SdD"
//    var uid: String? = "1833008990"
    
    lazy var userAccount = UserAccount()
    
    /// 用户登录标记[计算型属性]
    var userLogon: Bool {
//        return accessToken != nil
        return userAccount.access_token != nil
    }
    
    /// 专门负责拼接token的网络请求方法
    ///
    /// - Parameters:
    ///   - method: 网络请求方式GET/POST
    ///   - URLString: url接口
    ///   - parameters: 参数字典
    ///   - completion: 完成的回调
    func tokenRequest(method: HTTPMethod = .GET, URLString: String, parameters: Any?, completion:@escaping ( _ json: Any?, _ isSuccess: Bool)->()) {
        
        // 处理token字典
        // 1.判断token是否为nil，为nil直接返回 程序执行过程中，token 一般不会为 nil
        guard let token = userAccount.access_token else {
            
            // 发送通知，提示用户登录
            print("没有token, 需要登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserShouldLogonNotification), object: nil)
            
            completion(nil, false)
            
            return
        }
        
        // 2.判断参数字典是否存在，如果为nil，则新建一个字典
        var parameters = parameters as? [String: Any]
        
        if parameters == nil {
            
            parameters = [String: Any]()
            
        }
        
        // 参数字典在此处一定有值，可用 ‘!’ 解包
        parameters!["access_token"] = token
        
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
        
    }
    
    func request(method: HTTPMethod = .GET, URLString: String, parameters: Any?, completion:@escaping ( _ json: Any?, _ isSuccess: Bool)->()) {
        
        let success = { (task:URLSessionDataTask, json: Any?)->() in
            
            completion(json, true)
        
        }
        
        let failure = { (task:URLSessionDataTask?, error: Error )->() in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {// 403:  token过期
                
                print("token 过期")
                
                // 发送通知，提示用户再次登录
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserShouldLogonNotification), object: "token过期")
            }
            
            print("网络请求错误: \(error)")
            
            completion(nil, false)
   
        }
        
        if method == .GET {
            
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
//            get(URLString, parameters: parameters, progress: { (Progress) in
//                let p = Progress.completedUnitCount / Progress.totalUnitCount
//                SVProgressHUD.showProgress(Float(p))
//                print("进度:",p)
//            }, success: success, failure: failure)
            
        }
        else
        {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
 
    }
    
    
}
